package it.isa.demo.config.mybatis;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

/**
 * @author Corgile
 * @date 2022-02-27
 */
@Configuration
@MapperScan(basePackages = "it.isa.demo.mapper.one",
		sqlSessionFactoryRef = "primarySqlSessionFactory",
		sqlSessionTemplateRef = "primarySqlSessionTemplate")
public class MyBatisConfigOne {

	@Bean(name = "primarySqlSessionFactory")
	SqlSessionFactory primarySqlSessionFactory(
			@Qualifier(value = "primaryDataSource") DataSource primary
	) throws Exception {
		SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
		bean.setDataSource(primary);
		bean.setMapperLocations(new PathMatchingResourcePatternResolver()
				.getResources("classpath*:mapping/one/*.xml"));
		return bean.getObject();
	}

	@Primary
	@Bean(name = "primarySqlSessionTemplate")
	SqlSessionTemplate primarySqlSessionTemplate(
			@Qualifier("primarySqlSessionFactory") SqlSessionFactory sessionFactory) {
		return new SqlSessionTemplate(sessionFactory);
	}
}
